#!/bin/bash

FILE_OLD=./old
FILE_NEW=./new
OLD_DK=./old_dk

declare -A OLD_VER=()

function read_old() {
    OLD_VER[$1]=$2
}

function update() {
    FILENAME=$1

    TMP=${FILENAME:0-6:6}
    if [[ $TMP == 'tar.gz' ]]
    then
        TMP=${FILENAME:0:0-7}
        NAME=${TMP%-*}
        VER=${TMP##*-}
    fi

    OLD=${OLD_VER[$NAME]}
    if [[ $VER != $OLD ]]
    then
        echo "......................................update $FILENAME from $OLD to $VER"
        docker load < ./img/$FILENAME

        echo $NAME:$OLD >> $OLD_DK
    fi
}

#========================================

if [ -e $FILE_OLD ]
then
    rm -f $FILE_OLD
fi

if [ -e $FILE_NEW ]
then
    rm -f $FILE_NEW
fi

if [ -e $OLD_DK ]
then
    rm -f $OLD_DK
fi

echo "......................................stop servers"

DOCKER_COMP=../docker-compose.yml

if [ -e $DOCKER_COMP ]
then
    mkdir tmp

    cp $DOCKER_COMP ./tmp
    cp ./stop ./tmp
    cd tmp
    ./stop
    cd ..

    rm -rf ./tmp
fi

echo "......................................clear container"

DKC=`docker container ls -a -q -f status=exited`
if [ "$DKC" ]
then
    docker container rm $DKC
fi

echo "......................................diff image version"

docker image ls --format "{{.Repository}} {{.Tag}}" > $FILE_OLD
ls img -1 > $FILE_NEW

if [ -e $FILE_OLD ]
then
    while read v
    do
        read_old $v
    done < $FILE_OLD
fi

echo
echo "......................................start update"
echo

if [ -e $FILE_NEW ]
then
    while read v
    do
        update $v
    done < $FILE_NEW
fi

echo "......................................update docker-compose config"

if [ -e ../docker-compose.yml ]
then
    rm -f ../docker-compose.yml
fi
cp ./docker-compose.yml ../

echo "......................................start servers"
./up

if [ -e $OLD_DK ]
then
    while read v
    do
        echo "......................................remove old image $v"
        docker rmi $v
    done < $OLD_DK
fi
